export async function onMessage(msg, configObj) {
	const { config, startTime, bot, chatGPTClient } = configObj;
	// 避免重复发送
	if (msg.date() < startTime) {
		return;
	}
	console.log('msg', msg);

	const contact = msg.talker();
	const receiver = msg.to();
	const content = msg.text().trim();
	const room = msg.room();
	const alias = (await contact.alias()) || (await contact.name());
	const msgType = msg.type();
	// console.log('msgType', msgType);
	// console.log('bot.Message', bot.Message);
	// console.log('bot.Message.Type', msgType);
	const isText = msgType === bot.Message.Type.Text;
	if (msg.self()) {
		return;
	}
	// talkerId: '@2ad324a6177052ea42eeb0328a4ed604a9b1e335b5f00609a06f3197b04b40c3',
	// listenerId: '@1a19e6cfd27057e06016964a032f7e3554fc8a453d2488aa1680ff0a461f7134',

	if (room && isText) {
		const topic = await room.topic();
		console.log(
			`Group name: ${topic} talker: ${await contact.name()} content: ${content}`
		);

		const pattern = RegExp(
			`^@${receiver.name()}\\s+${config.groupKey}[\\s]*`
		);
		// 是否@我
		if (await msg.mentionSelf()) {
			if (pattern.test(content)) {
				const groupContent = content.replace(pattern, '');
				chatGPTClient.replyMessage(room, groupContent);
				return;
			} else {
				console.log(
					'Content is not within the scope of the customizition format'
				);
			}
		}
	} else if (isText) {
		console.log(`talker: ${alias} content: ${content}`);
		if (content.startsWith(config.privateKey) || config.privateKey === '') {
			let privateContent = content;
			if (config.privateKey === '') {
				privateContent = content
					.substring(config.privateKey.length)
					.trim();
			}
			await contact.say('请稍候，GPT正在思考...');
			chatGPTClient.replyMessage(contact, privateContent);
		} else {
			console.log(
				'Content is not within the scope of the customizition format'
			);
		}
	}
}
